<template>
  <div class="layui-container">
    <div class="layui-row">
      <div class="layui-col-lg3">
        <form class="layui-form" action="">
          <div class="layui-form-item">
            <label class="layui-form-label">订单状态</label>
            <div class="layui-input-block">
              <select name="orderStatus" lay-verify="required" lay-filter="changeOrderStatus">
                <option value="未付款" selected>未付款</option>
                <option value="已付款">已付款</option>
                <option value="已失效">已失效</option>
                <option value="已使用">已使用</option>
                <option value="全部">全部</option>
              </select>
            </div>
          </div>
        </form>
      </div>
      <div class="layui-col-lg5 layui-col-lg-offset1">
        <div class="block">
          <span class="demonstration">放映时间</span>
          <el-date-picker
            v-model="movieStartEndTime"
            :editable="false"
            type="daterange" :clearable="false"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            @change="queryMovieStartEndTime">
          </el-date-picker>
        </div>
      </div>
    </div>
    <div class="layui-row">
      <div class="layui-col-lg4">
        <div class="layui-form">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">订单时间</label>
              <div class="layui-input-inline">
                <input type="text" class="layui-input" id="test16" placeholder="开始 到 结束" lay-filter="queryOrderTime">
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="layui-col-lg1">
        <span style="color: red">搜索</span>
      </div>
      <div class="layui-col-lg2" style="margin-left: -50px">
        <el-input v-model="searchOrder" placeholder="搜索订单" clearable suffix-icon="el-icon-search"
                  @change="searchOrderInput"
                  @clear="clearSearch"></el-input>
      </div>
    </div>
    <div class="layui-row">
      <div class="layui-col-lg1">
        <h3 style="color: red;text-shadow: 2px 2px violet">未付款:{{noPayCount}}</h3>
      </div>
      <div class="layui-col-lg1">
        <h3 style="color: #0000FF;text-shadow: 2px 2px #F08080">已付款:{{hasPayCount}}</h3>
      </div>
      <div class="layui-col-lg1">
        <h3 style="color: #D15FEE;text-shadow: 2px 2px #CAFF70">已失效:{{loseCount}}</h3>
      </div>
      <div class="layui-col-lg1">
        <h3 style="color: #00CD00;text-shadow: 2px 2px #436EEE">已使用:{{hasUseCount}}</h3>
      </div>
      <div class="layui-col-lg1 ">
        <h3 style="color: #FFB90F;text-shadow: 2px 2px #A52A2A">总消费:{{totalConsumption}}</h3>
      </div>
    </div>
    <div class="layui-row" v-if="orderTableExchange.length!=0">
      <table class="layui-table">
        <colgroup>
          <col width="100">
          <col width="150">
          <col width="100">
          <col width="80">
          <col width="80">
          <col width="120">
          <col width="120">
          <col width="90">
          <col width="60">
          <col width="120">
          <col width="100">
        </colgroup>
        <thead>
        <tr>
          <th>影院</th>
          <th>地址</th>
          <th>电影</th>
          <th>厅号</th>
          <th>座号</th>
          <th>开始</th>
          <th>结束</th>
          <th>时长</th>
          <th>票价</th>
          <th>下单时间</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="(item,idx) in orderTablePaging" :key="idx">
          <td v-if="item.pay_status=='未付款'"><input type="checkbox"
                                                   @change="payMoney(item.id,item.movie_ticket_price,$event.target.checked)">{{item.movie_theatre_name}}
          </td>
          <td v-else>{{item.movie_theatre_name}}</td>
          <td>{{item.movie_theatre_address}}</td>
          <td>{{item.movie_name}}</td>
          <td>{{item.video_hall_name}}</td>
          <td>{{item.seat.split(",")[0]+'排'+item.seat.split(",")[1]+'座'}}</td>
          <td>{{item.movie_start_time}}</td>
          <td>{{item.movie_end_time}}</td>
          <td>{{item.movie_duration}}分钟</td>
          <td>{{item.movie_ticket_price}}</td>
          <td>{{item.order_time}}</td>
          <td v-if="item.pay_status=='未付款'" style="color: green;cursor: pointer" @click="singlePay(item)">扫码支付</td>
          <td v-if="item.pay_status=='已付款'"><h4 style="color: red;cursor: pointer">退票/改签</h4><h4
            style="color: #474747;cursor: pointer" @click="lookTicket(item.id)">查看票</h4></td>
          <td v-if="item.pay_status=='已使用'&&item.comment_status=='未评论'" style="color: blue;cursor: pointer"
              @click="writeComment(item)">写评论
          </td>
          <td v-if="item.pay_status=='已使用'&&item.comment_status=='已评论'" style="color: #B3EE3A">已评论</td>
          <td v-if="item.pay_status=='已失效'" style="color: orange;cursor: pointer">重新购买</td>
        </tr>
        </tbody>
      </table>
    </div>
    <div class="layui-row" v-if="orderTableExchange.length!=0">
      <div class="layui-col-lg3">
        <el-pagination
          background
          layout="prev, pager, next" :page-size="pageSize" @current-change="currentChange"
          @prev-click="prevClick" @next-click="nextClick" :current-page="startPage"
          :total="orderTableExchange.length">
        </el-pagination>
      </div>
      <div class="layui-col-lg3 layui-col-lg-offset6" style="text-align: center" v-if="moneySum.length!=0">
        <h1 style="color: red;text-shadow: 2px 2px violet">总计${{moneyCount}}
          <button type="button" class="layui-btn layui-btn-radius layui-btn-danger" @click="batchPay">批量支付</button>
        </h1>
      </div>
    </div>
    <div class="layui-row" v-if="orderTableExchange.length==0">
      <div style="border-bottom: 1px #E5E5E5 solid">
        <div class="layui-row" style="text-align: center">
          <h1>空空如也</h1>
        </div>
      </div>
    </div>
    <div class="layui-row">
      <button @click="test">测试</button>
    </div>
    <el-dialog
      title="请在放映时间结束前使用,过期概不负责"
      :visible.sync="centerDialogVisible"
      width="30%"
      center>
      <vue-qr bgSrc="static/images/默认头像.jpeg" logoSrc="static/images/暂无热映.jpg"
              :text="codeContent" colorDark="yellow" :size="400" colorLight="pink"
              style="margin-left: 13px"></vue-qr>
      <span slot="footer" class="dialog-footer">
    <el-button @click="centerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
    <el-dialog
      :visible.sync="commentDialogVisible" :show-close="false"
      width="50%"
      center>
      <div class="layui-fluid" style="height: 400px" v-if="active==0">
        <div class="layui-row">
          <div class="layui-col-lg7">
            <el-form ref="form" label-width="80px">
              <el-form-item label="电影评价">
                <el-input type="textarea" v-model="movieCommentContent" :rows="8"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-lg1">
            <h4>评分</h4>
          </div>
          <div class="layui-col-lg3">
            <el-rate
              v-model="movieRate"
              :colors="colors">
            </el-rate>
          </div>
        </div>
      </div>
      <div class="layui-fluid" style="height: 400px" v-if="active==1">
        <div class="layui-row">
          <div class="layui-col-lg7">
            <el-form ref="form" label-width="80px">
              <el-form-item label="影院评价">
                <el-input type="textarea" v-model="cinemaCommentContent" :rows="8"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div class="layui-row">
          <div class="layui-col-lg1">
            <h4>评分</h4>
          </div>
          <div class="layui-col-lg3">
            <el-rate
              v-model="cinemaRate"
              :colors="colors">
            </el-rate>
          </div>
        </div>
      </div>
      <el-steps :active="active" finish-status="success">
        <el-step title="电影评价"></el-step>
        <el-step title="影院评价"></el-step>
        <el-step title="提交评论"></el-step>
      </el-steps>
      <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
    </el-dialog>
  </div>
</template>

<script>
    import VueQr from 'vue-qr'
    export default {
        name: "view_order",
        data() {
            return {
                generalUser: "",
                orderTable: [],
                startPage: 1,
                pageSize: 5,
                orderTablePaging: [],
                orderTableExchange: [],
                orderStatus: "未付款",
                movieStartEndTime: "",
                exchangeBackup: [],
                orderTime: [],
                searchOrder: "",
                moneySum: [],
                htmls: "",
                centerDialogVisible: false,
                codeContent: "",
                commentDialogVisible: false,
                active: 0,
                movieCommentContent: "",
                movieRate: 0,
                colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
                cinemaCommentContent: "",
                cinemaRate: 0,
                writeCommentAction: ""
            }
        },
        components: {
            VueQr
        },
        created() {
            let user = sessionStorage.getItem("generalUser")
            if (user == null) {
                this.$router.push({
                    name: "login_register_page"
                })
            } else {
                this.generalUser = JSON.parse(user)
                let orderId = sessionStorage.getItem("payInfo")
                if (orderId != null) {
                    this.queryAlipay()
                } else {
                    this.getOrderTablePc()
                }
            }
        },
        mounted() {
            layui.use('laydate', () => {
                var laydate = layui.laydate;
                var a = this
                laydate.render({
                    elem: '#test16'
                    , type: 'date'
                    , range: '到'
                    , format: 'yyyy-MM-dd',
                    done(value) {
                        a.orderTime = value.split('到');
                        if (a.exchangeBackup.length == 0) {
                            a.exchangeBackup = a.orderTableExchange
                        } else {
                            a.orderTableExchange = a.exchangeBackup
                            a.exchangeBackup = []
                        }
                        let startTime = Date.parse(a.orderTime[0])
                        let endTime = Date.parse(a.orderTime[1])
                        let exchangeTemp = []
                        for (let i = 0; i < a.orderTableExchange.length; i++) {
                            let startDay = new Date(a.orderTableExchange[i].order_time)
                            let year = startDay.getFullYear()
                            let month = startDay.getMonth() + 1
                            let day = startDay.getDate()
                            let startDayFinal = Date.parse(year + "-" + month + "-" + day)
                            if (startDayFinal >= startTime && startDayFinal <= endTime) {
                                exchangeTemp.push(a.orderTableExchange[i])
                            }
                        }
                        a.orderTableExchange = exchangeTemp
                        a.getOrderTablePaging()
                    }
                });
            });
            layui.use('form', () => {
                var form = layui.form;
                form.render('select');
                form.on('select(changeOrderStatus)', (data) => {
                    this.orderStatus = data.value
                })
            });
        },
        methods: {
            test() {
                console.log(this.writeCommentAction)
            },
            test2() {
                this.$axios.get('/api/queryAlipay', {
                    params: {
                        WIDTQout_trade_no: "444444"
                    }
                }).then((res) => {
                    console.log(res)
                })
            },
            getOrderTablePc() {
                this.$axios.get('/api/tato/getOrderTablePc', {
                    params: {
                        generalUserId: this.generalUser.id
                    }
                }).then((res) => {
                    for (let i = 0; i < res.data.length; i++) {
                        this.orderTable.push(res.data[i])
                    }
                    this.getOrderTableExchange()
                })
            },
            getOrderTableExchange() {
                this.orderTableExchange = []
                if (this.orderStatus == "全部") {
                    this.orderTableExchange = this.orderTable
                } else {
                    for (let i = 0; i < this.orderTable.length; i++) {
                        if (this.orderTable[i].pay_status == this.orderStatus) {
                            this.orderTableExchange.push(this.orderTable[i])
                        }
                    }
                }
                this.getOrderTablePaging()
            },
            getOrderTablePaging() {
                this.orderTablePaging = []
                let start = (this.startPage - 1) * this.pageSize
                for (let i = start; i < start + this.pageSize; i++) {
                    if (this.orderTableExchange[i] == undefined) {
                        break
                    } else {
                        this.orderTablePaging.push(this.orderTableExchange[i])
                    }
                }
            },
            currentChange(e) {
                this.startPage = e
                if (this.searchOrder) {
                    this.getOrderTablePaging()
                } else {
                    this.getOrderTableExchange()
                }
            },
            prevClick() {
                this.startPage--
                if (this.searchOrder) {
                    this.getOrderTablePaging()
                } else {
                    this.getOrderTableExchange()
                }
            },
            nextClick() {
                this.startPage++
                if (this.searchOrder) {
                    this.getOrderTablePaging()
                } else {
                    this.getOrderTableExchange()
                }
            },
            queryMovieStartEndTime() {
                if (this.exchangeBackup.length == 0) {
                    this.exchangeBackup = this.orderTableExchange
                } else {
                    this.orderTableExchange = this.exchangeBackup
                    this.exchangeBackup = []
                }
                let startTime = Date.parse(this.movieStartEndTime[0])
                let endTime = Date.parse(this.movieStartEndTime[1])
                let exchangeTemp = []
                for (let i = 0; i < this.orderTableExchange.length; i++) {
                    let startDay = new Date(this.orderTableExchange[i].movie_start_time)
                    let year = startDay.getFullYear()
                    let month = startDay.getMonth() + 1
                    let day = startDay.getDate()
                    let startDayFinal = Date.parse(year + "-" + month + "-" + day)
                    if (startDayFinal >= startTime && startDayFinal <= endTime) {
                        exchangeTemp.push(this.orderTableExchange[i])
                    }
                }
                this.orderTableExchange = exchangeTemp
                this.getOrderTablePaging()
            },
            searchOrderInput() {
                let searchResult = []
                this.startPage = 1
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].movie_theatre_name.indexOf(this.searchOrder) != -1 || this.orderTable[i].movie_theatre_address.indexOf(this.searchOrder) != -1 ||
                        this.orderTable[i].movie_name.indexOf(this.searchOrder) != -1 || this.orderTable[i].video_hall_name.indexOf(this.searchOrder) != -1
                    ) {
                        searchResult.push(this.orderTable[i])
                    }
                }
                if (searchResult.length != 0) {
                    this.orderTableExchange = searchResult
                    this.getOrderTablePaging()
                } else {
                    this.searchOrder = "没有查询到结果"
                }
            },
            clearSearch() {
                this.searchOrder = ""
                this.getOrderTableExchange()
            },
            payMoney(orderId, price, e) {
                if (e) {
                    let temp = {
                        orderId: orderId,
                        price: price
                    }
                    this.moneySum.push(temp)
                } else {
                    for (let i = 0; i < this.moneySum.length; i++) {
                        if (this.moneySum[i].orderId == orderId) {
                            this.moneySum.splice(i, 1)
                        }
                    }
                }
            },
            singlePay(item) {
                this.$confirm('此操作将前往支付页面, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这是数据库的订单id
                    let id = item.id
                    //这是给支付宝的订单号UUID
                    let orderId = this.getUUID()
                    let payMoney = item.movie_ticket_price
                    let orderSubject = "电影票"
                    let orderDetail = "一张电影票"
                    let temp = {
                        id: id,
                        orderId: orderId
                    }
                    sessionStorage.setItem("payInfo", JSON.stringify(temp))
                    this.goToAliPay(orderId, payMoney, orderSubject, orderDetail)
                }).catch(() => {

                });
            },
            goToAliPay(orderId, payMoney, orderSubject, orderDetail) {
                var params = new URLSearchParams();
                params.append('orderId', orderId);
                params.append('payMoney', payMoney);
                params.append('orderSubject', orderSubject);
                params.append('orderDetail', orderDetail);
                this.$axios.post('/api/alipay', params).then((res) => {
                    console.log(res)
                    if (res.status === 200) {
                        this.$router.push({
                            path: "/alipay_page",
                            query: {
                                htmls: res.data
                            }
                        })
                    }
                })
            },
            getUUID() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
                s[8] = s[13] = s[18] = s[23] = "-";
                var uuid = s.join("");
                return uuid;
            },
            queryAlipay() {
                let temp = JSON.parse(sessionStorage.getItem("payInfo"))
                if (temp != null) {
                    this.$axios.get('/api/queryAlipay', {
                        params: {
                            WIDTQout_trade_no: temp.orderId
                        }
                    }).then((res) => {
                        if (res.data.alipay_trade_query_response.trade_status = "TRADE_SUCCESS") {
                            //接下来是发请求修改支付状态
                            this.$axios.get('/api/tato/changeOrderStatusToHasPayPc', {
                                params: {
                                    orderId: temp.id
                                }
                            }).then((res) => {
                                if (res.data == 1) {
                                    this.$notify({
                                        title: '成功',
                                        message: '支付成功',
                                        type: 'success'
                                    });
                                    this.getOrderTablePc()
                                }
                            })
                        } else {
                            this.$notify.error({
                                title: '错误',
                                message: '支付失败'
                            });
                        }
                    })
                    sessionStorage.removeItem("payInfo")
                }
            },
            batchPay() {
                this.$confirm('此操作将前往支付页面, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //这是一个数组
                    let id = ""
                    for (let i = 0; i < this.moneySum.length; i++) {
                        id += this.moneySum[i].orderId + "哈哈哈"
                    }
                    //这是给支付宝的订单号UUID
                    let orderId = this.getUUID()
                    let payMoney = 0
                    for (let i = 0; i < this.moneySum.length; i++) {
                        payMoney += this.moneySum[i].price
                    }
                    let orderSubject = "电影票"
                    let orderDetail = this.moneySum.length + "张电影票"
                    let temp = {
                        id: id,
                        orderId: orderId
                    }
                    sessionStorage.setItem("payInfo", JSON.stringify(temp))
                    this.goToAliPay(orderId, payMoney, orderSubject, orderDetail)
                }).catch(() => {

                });
            },
            lookTicket(id) {
                this.centerDialogVisible = true
                this.codeContent = "http://localhost:8089/tato/useMovieTicketPc?orderId=" + id
            },
            writeComment(e) {
                this.writeCommentAction = e
                this.active = 0
                this.movieCommentContent = ""
                this.movieRate = 0
                this.cinemaCommentContent = ""
                this.cinemaRate = 0
                this.commentDialogVisible = true
            },
            next() {
                if (this.active == 0) {
                    if (this.movieCommentContent.trim().length > 0 && this.movieRate != 0) {
                        this.active++
                    } else {
                        layer.alert('请认真填写评论和评分', {icon: 5});
                    }
                } else if (this.active == 1) {
                    if (this.cinemaCommentContent.trim().length > 0 && this.cinemaRate != 0) {
                        this.active++
                    } else {
                        layer.alert('请认真填写评论和评分', {icon: 5});
                    }
                } else if (this.active == 2) {
                    this.$confirm('评论一旦提交将不可修改, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let content = new URLSearchParams()
                        content.append("userId", this.writeCommentAction.general_user_id)
                        content.append("movieId", this.writeCommentAction.movie_id)
                        content.append("movieComment", this.movieCommentContent)
                        content.append("movieRate", this.movieRate)
                        content.append("cinemaId", this.writeCommentAction.movie_theatre_detail_id)
                        content.append("cinemaComment", this.cinemaCommentContent)
                        content.append("cinemaRate", this.cinemaRate)
                        content.append("commentStatus", this.writeCommentAction.comment_status)
                        content.append("orderId", this.writeCommentAction.id)
                        this.$axios.post('/api/tato/userCommentMovieAndCinemaPc', content).then((res) => {
                            if (res.data == 1) {
                                layer.msg('评论成功', {icon: 1});
                                this.commentDialogVisible = false
                                this.writeCommentAction.comment_status = "已评论"
                            } else if (res.data == 2) {
                                layer.msg('请不要重复评论', {icon: 2});
                                this.commentDialogVisible = false
                            }
                        })
                    }).catch(() => {

                    });
                }

            }
        },
        watch: {
            orderStatus() {
                this.startPage = 1
                this.movieStartEndTime = ""
                this.orderTime = []
                this.exchangeBackup = []
                this.getOrderTableExchange()
            }
        },
        computed: {
            moneyCount() {
                let sum = 0
                for (let i = 0; i < this.moneySum.length; i++) {
                    sum += this.moneySum[i].price
                }
                return sum
            },
            totalConsumption() {
                let allMoney = 0
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].pay_status == '已使用') {
                        allMoney += this.orderTable[i].movie_ticket_price
                    }
                }
                return allMoney
            },
            loseCount() {
                let num = 0
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].pay_status == '已失效') {
                        num++
                    }
                }
                return num
            },
            noPayCount() {
                let num = 0
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].pay_status == '未付款') {
                        num++
                    }
                }
                return num
            },
            hasPayCount() {
                let num = 0
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].pay_status == '已付款') {
                        num++
                    }
                }
                return num
            },
            hasUseCount() {
                let num = 0
                for (let i = 0; i < this.orderTable.length; i++) {
                    if (this.orderTable[i].pay_status == '已使用') {
                        num++
                    }
                }
                return num
            }
        }
    }
</script>

<style scoped>

</style>
